package com.ls.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ls.server.domain.ChatModel;
import com.ls.server.dto.ChatModelDTO;
import com.ls.server.dto.ChatQueryDTO;
import com.ls.server.mapper.ChatModelMapper;
import com.ls.server.service.ChatModelService;
import com.ls.server.vo.ChatModelVO;
import com.ls.server.vo.PageResult;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 聊天模型Service实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ChatModelServiceImpl extends ServiceImpl<ChatModelMapper, ChatModel> implements ChatModelService {

    @Override
    public List<ChatModelVO> listEnabledModels() {
        LambdaQueryWrapper<ChatModel> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ChatModel::getEnabled, true)
               .orderByAsc(ChatModel::getId);
        
        List<ChatModel> models = baseMapper.selectList(wrapper);
        return convertToVoList(models);
    }

    @Override
    public List<ChatModelVO> listAllModels() {
        List<ChatModel> models = baseMapper.selectList(null);
        return convertToVoList(models);
    }

    @Override
    public ChatModelVO getModelById(Long id) {
        ChatModel model = baseMapper.selectById(id);
        if (model == null) {
            return null;
        }
        return convertToVo(model);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean createModel(ChatModelDTO dto) {
        // 检查编码是否已存在
        LambdaQueryWrapper<ChatModel> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ChatModel::getCode, dto.getCode());
        if (baseMapper.selectCount(wrapper) > 0) {
            throw new RuntimeException("模型编码已存在");
        }
        
        ChatModel model = new ChatModel();
        BeanUtils.copyProperties(dto, model);
        return baseMapper.insert(model) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateModel(ChatModelDTO dto) {
        // 检查编码是否已存在(排除自身)
        LambdaQueryWrapper<ChatModel> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ChatModel::getCode, dto.getCode())
               .ne(ChatModel::getId, dto.getId());
        if (baseMapper.selectCount(wrapper) > 0) {
            throw new RuntimeException("模型编码已存在");
        }
        
        ChatModel model = new ChatModel();
        BeanUtils.copyProperties(dto, model);
        return baseMapper.updateById(model) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean enableModel(Long id, Boolean enabled) {
        ChatModel model = baseMapper.selectById(id);
        if (model == null) {
            return false;
        }
        
        model.setEnabled(enabled);
        return baseMapper.updateById(model) > 0;
    }

    @Override
    public PageResult<ChatModelVO> page(ChatQueryDTO queryDTO) {
        Page<ChatModel> page = new Page<>(queryDTO.getPageNum(), queryDTO.getPageSize());
        LambdaQueryWrapper<ChatModel> wrapper = new LambdaQueryWrapper<>();
        
        // 添加查询条件
        if (StringUtils.hasText(queryDTO.getKeyword())) {
            wrapper.like(ChatModel::getName, queryDTO.getKeyword())
                   .or()
                   .like(ChatModel::getCode, queryDTO.getKeyword())
                   .or()
                   .like(ChatModel::getDescription, queryDTO.getKeyword());
        }
        
        // 排序
        wrapper.orderByDesc(ChatModel::getCreateTime);
        
        IPage<ChatModel> result = baseMapper.selectPage(page, wrapper);
        List<ChatModelVO> voList = convertToVoList(result.getRecords());
        
        return new PageResult<>(voList, result.getTotal());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean delete(Long id) {
        return baseMapper.deleteById(id) > 0;
    }
    
    /**
     * 将实体转换为VO
     */
    private ChatModelVO convertToVo(ChatModel model) {
        ChatModelVO vo = new ChatModelVO();
        BeanUtils.copyProperties(model, vo);
        return vo;
    }
    
    /**
     * 将实体列表转换为VO列表
     */
    private List<ChatModelVO> convertToVoList(List<ChatModel> models) {
        if (models == null || models.isEmpty()) {
            return new ArrayList<>();
        }
        return models.stream()
                .map(this::convertToVo)
                .collect(Collectors.toList());
    }
}
